package com.ayf.payment.game.api.channel.zhuofutong.util;

import com.ayf.payment.game.api.utils.MD5Util;
import com.swwx.charm.commons.lang.utils.LogPortal;

import java.util.*;

import static com.ayf.payment.game.api.channel.zhuofutong.util.RSAUtils.urlEncode;

/**
 * @author wwl
 * @description:
 * @date 2021/2/23 10:15
 */
public class SignUtils {
    public static String sign(Map<String,String> map, String key){
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        LogPortal.debug("签名原文[{}]",preStr.concat("&key=").concat(key));
        return  MD5Util.sign(preStr, "&key=" + key);
    }


    /** <一句话功能简述>
     * <功能详细描述>验证返回参数
     * @param params
     * @param key
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean checkParam(Map<String,String> params,String key,String input_cgarset){
        boolean result = false;
        if(params.containsKey("sign")){
            String sign = params.get("sign");
            params.remove("sign");
            StringBuilder buf = new StringBuilder((params.size() +1) * 10);
            SignUtils.buildPayParams(buf,params,false);
            String preStr = buf.toString();
            String signRecieve = MD5Util.sign(preStr, "&key=" + key);
            result = sign.equalsIgnoreCase(signRecieve);
            params.put("sign",sign);

        }
        return result;
    }

    /**
     * 过滤参数
     * @author
     * @param sArray
     * @return
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>(sArray.size());
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * @author
     * @param payParams
     * @return
     */
    public static void buildPayParams(StringBuilder sb,Map<String, String> payParams,boolean encoding){
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for(String key : keys){
            sb.append(key).append("=");
            if(encoding){
                sb.append(urlEncode(payParams.get(key)));
            }else{
                sb.append(payParams.get(key));
            }
            sb.append("&");
        }
        sb.setLength(sb.length() - 1);
    }

}
